package com.youlu.campus.website.service.impl;

import com.youlu.campus.common.exception.BusinessException;
import com.youlu.campus.website.entity.ActivityType;
import com.youlu.campus.website.entity.ActivityTypePageQuery;
import com.youlu.campus.website.repositories.ActivityTypeRepository;
import com.youlu.campus.website.service.ActivityTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 活动简介类型
 */
@Service
public class ActivityTypeServiceImpl implements ActivityTypeService {

    @Autowired
    private ActivityTypeRepository activityTypeRepository;

    @Resource(name = "websiteMongoTemplate")
    private MongoTemplate mongoTemplate;

    /**
     * 保存标题类型（新增或更新）
     *
     * @param activityType 标题类型对象
     * @return 保存后的标题类型
     */
    @Override
    public ActivityType save(ActivityType activityType) {
        // 检查编码是否已存在（新增时）
        if (StringUtils.isAnyBlank(activityType.getType(), activityType.getName())) {
            throw new BusinessException("参数异常");
        }
        ActivityType old = activityTypeRepository.findByType(activityType.getType());
        if (old != null) {
            if (StringUtils.isBlank(activityType.getId()) || !activityType.getId().equals(old.getId())) {
                throw new IllegalArgumentException("标题类型编码已存在");
            }
        }
        LocalDateTime now = LocalDateTime.now();
        if (activityType.getId() == null) {
            activityType.setCreateTime(now);
        }
        activityType.setUpdateTime(now);
        return activityTypeRepository.save(activityType);
    }

    /**
     * 根据ID查询标题类型
     *
     * @param id 主键ID
     * @return 标题类型
     */
    @Override
    public ActivityType getTypeById(String id) {
        Optional<ActivityType> optional = activityTypeRepository.findById(id);
        return optional.orElse(null);
    }

    /**
     * 查询所有标题类型
     *
     * @return 标题类型列表
     */
    @Override
    public List<ActivityType> listAllTypes() {
        return activityTypeRepository.findAll();
    }

    /**
     * 根据显示条数  启用的标题类型
     *
     * @return 启用的标题类型列表
     */
    @Override
    public List<ActivityType> listEnabledType(int pageSize) {
        Sort sort = Sort.by(Sort.Direction.ASC, "sort");
        Pageable pageable = PageRequest.of(0, pageSize, sort); // 第0页，每页5条，按sort升序
        return activityTypeRepository.findByEnabled(true, pageable);
    }

    /**
     * 根据ID删除标题类型
     *
     * @param id 主键ID
     */
    @Override
    public void delete(String id) {
        activityTypeRepository.deleteById(id);
    }

    /**
     * 启用/禁用标题类型
     *
     * @param id        主键ID
     * @param isEnabled 是否启用
     * @return 更新后的标题类型
     */
    @Override
    public ActivityType toggleTypeStatus(String id, boolean isEnabled) {
        ActivityType activityType = activityTypeRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("标题类型不存在: " + id));

        activityType.setEnabled(isEnabled);
        activityType.setUpdateTime(LocalDateTime.now());
        return activityTypeRepository.save(activityType);
    }

    @Override
    public Page<ActivityType> findByPage(ActivityTypePageQuery pageQuery) {
        Sort sort = Sort.by(Sort.Direction.DESC, "sort");
        Pageable pageable = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), sort);

        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getName())) {
            query.addCriteria(Criteria.where("name").regex(pageQuery.getName(), "i"));
        }
        if (pageQuery.getEnabled() != null) {
            query.addCriteria(Criteria.where("enabled").is(pageQuery.getEnabled()));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, ActivityType.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<ActivityType> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = mongoTemplate.find(query, ActivityType.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    @Override
    public ActivityType findByType(String type) {
        return activityTypeRepository.findByType(type);
    }

    @Override
    public List<ActivityType> findByTypeIn(List<String> types) {
        return activityTypeRepository.findByTypeInOrderBySortAsc(types);
    }
}
